from django.shortcuts import render
from scheduler_package.api.base import View
from django.http import JsonResponse
from hashlib import sha256
from django.core.cache import cache
from . import models as user_models
from scheduler_package.tasks.task import add_user
from apscheduler.triggers.interval import IntervalTrigger #时间间隔
from utils.ascync_task import run_scheduler_task
from uuid import uuid4
# Create your views here.
class UserView(View):
    def make_password(self,pwd,account):
        sha = sha256()
        sha.update(pwd.encode('utf-8'))
        sha.update(account.encode('utf-8'))
        sha.update((pwd[-1] + account[0] + pwd[0] + account[-1]).encode('utf-8'))
        return sha.hexdigest()

    def get(self,request):
        user_id = self.data.get('user_id')
        if user_id:
            user_obj = user_models.UserModel.objects.filter(pk=user_id).first()
            ret = {
                'code': 200,
                'status': 'success',
                'result': {
                    'id': user_obj.pk,
                    'name': user_obj.name,
                    'account': user_obj.account,
                    'phone': user_obj.phone
                }
            }
            return JsonResponse(ret)
        else:
            ret = {
                'code': 200,
                'status': 'success',
                'result': []
            }
            data = cache.get(CacheUserJobView.KEY)
            print(data,'cache中的数据')
            if data:
                ret['result'] = data
                ret['type'] = 'cache'
                return JsonResponse(ret)
            user_objs = user_models.UserModel.objects.all()
            for user_obj in user_objs:
                dic = {
                    'id': user_obj.pk,
                    'name': user_obj.name,
                    'account': user_obj.account,
                    'phone': user_obj.phone
                }
                ret['result'].append(dic)
            ret['type'] = 'sql'
            return JsonResponse(ret)

    def post(self,request):
        data = self.data
        account = data.get('account')
        password = data.get('password')
        obj = user_models.UserModel.objects.filter(account=account)
        ret = {
            'code': 200,
            'status': 'success'
        }
        if obj:
            ret['code'] = 400
            ret['status'] = '账户名已经存在'
            return JsonResponse(ret)
        else:
            data['password'] = self.make_password(password,account)
            user_models.UserModel.objects.create(**data)
            return JsonResponse(ret)

    def put(self,request):
        data = self.data
        user_id = data.get('id')
        password = data.get('password')
        ret = {
            'code': 200,
            'status': 'success'
        }
        user_obj = user_models.UserModel.objects.filter(pk = user_id)
        if not user_obj:
            ret['code'] = 400
            ret['status'] = '查询不到用户信息'
            return JsonResponse(ret)
        if password:
            account = user_obj.first().account
            data['password'] = self.make_password(password,account)
        if data['account']:
            data.pop('account')

        user_obj.update(**data)
        return JsonResponse(ret)


class TestCacheView(View):
    def get(self,request):
        ret = {
            'code': 200,
            'status': 'success'
        }
        data = cache.get('test')
        ret['result'] = data
        return JsonResponse(ret)

    def post(self,request):
        cache.set('test',{'name':'test','age':12},timeout=3*60)
        ret = {
            'code': 200,
            'status': 'success'
        }
        return JsonResponse(ret)

class CacheUserJobView(View):
    KEY = 'all-user-info'
    TIMEOUT = 3
    @classmethod
    def cache_user_info(cls,timeout,key):
        from scheduler_package.logger import scheduler_logger
        user_objs = user_models.UserModel.objects.all()
        data = []
        for user_obj in user_objs:
            dic = {
                'id': user_obj.pk,
                'name': user_obj.name,
                'account': user_obj.account,
                'phone': user_obj.phone
            }
            data.append(dic)
        scheduler_logger.info(f'缓存用户信息到cache中，执行完成')
        cache.set(key, data,timeout = (timeout+3)*60)
    def post(self,request):
        job_id = self.data.get('job_id','cache-all-user-job-id')
        data_dict = {
            "timeout":self.TIMEOUT,
            "key":self.KEY,
        }
        run_scheduler_task(
            self.cache_user_info,job_id,'将所有的用户信息缓存到cache中',data_dict
        )
        ret = {
            'code': 200,
            'status': 'success'
        }
        return JsonResponse(ret)

    def func_test(self):
        users = cache.get(self.KEY)
        print(f'cache获取到用户信息{users}')
        return users
    def put(self,request):
        run_scheduler_task(
            self.func_test,
            'get-cache-users',
            '从cache获取用户信息'
        )
        ret = {
            'code': 200,
            'status': 'success',
        }
        return JsonResponse(ret)
class SchedulerCreateUser(View):
    def get(self,request):
        name = request.GET.get('name')
        account = request.GET.get('account')
        password = request.GET.get('password')
        phone = request.GET.get("phone")
        dic = {
            'name':name,
            'account':account,
            'password':password,
            'phone':phone
        }
        task_id = f'create_user:{uuid4()}'
        task_name = f'创建账户任务，name={name},account={account},phone={phone}'
        run_scheduler_task(add_user,task_id,task_name,dic)
        ret = {
            'code': 200,
            'status': 'success'
        }
        return JsonResponse(ret)